import HandleBtn from '@/components/HandleBar/btn';
import { ProTable, type ProColumns } from '@/components/Pro';
import {
  historyDataControllerHistoryDataExport as exportDataReport,
  historyDataControllerPcsDataPage,
} from '@/services/ess/historicalData';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { downloadFetch } from '@/utils/downloadFile';
import { Link, useIntl } from '@umijs/max'; // 引入 useIntl
import { message } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import React, { useEffect, useMemo, useState } from 'react';

interface Props {
  tabIndex?: string;
  deviceCode?: string;
  deviceType?: string;
  areaId?: string;
  selectedKeys?: string[];
}

const PCSDetails: React.FC<Props> = ({ deviceCode, deviceType, areaId, selectedKeys }) => {
  const intl = useIntl(); // 使用 useIntl 获取国际化函数

  const [data, setData] = useState<API.PcsPageData[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [params, setParams] = useState({
    current: 1,
    pageSize: 20,
    startDate: dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
    endDate: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
  });
  const [deviceWorkStatus, setDeviceWorkStatus] = useState<{ [key: string]: string }>({});
  const [deviceOnlineStatus, setDeviceOnlineStatus] = useState<{ [key: string]: string }>({});
  const [, setPcsStatus] = useState<{ [key: string]: string }>({});
  const [, setPcsFault] = useState<{ [key: string]: string }>({});
  const [selectedColumns, setSelectedColumns] = useState<string[]>([]);

  useEffect(() => {
    const fetchAllDictInfo = async () => {
      const [workStatus, onlineStatus, pcsStatus, pcsFault] = await Promise.all([
        fetchDictInfo(DATABASE_TYPE_ENUM.WORK_STATUS),
        fetchDictInfo(DATABASE_TYPE_ENUM.ONLINE_STATUS),
        fetchDictInfo(DATABASE_TYPE_ENUM.BREAKER_STATUS),
        fetchDictInfo(DATABASE_TYPE_ENUM.BREAKER_BREAKDOWN),
      ]);

      setDeviceWorkStatus(Object.fromEntries(workStatus.map(({ label, value }) => [value, label])));
      setDeviceOnlineStatus(
        Object.fromEntries(onlineStatus.map(({ label, value }) => [value, label])),
      );
      setPcsStatus(Object.fromEntries(pcsStatus.map(({ label, value }) => [value, label])));
      setPcsFault(Object.fromEntries(pcsFault.map(({ label, value }) => [value, label])));
    };

    fetchAllDictInfo();
  }, []);

  const initialColumns: ProColumns<any>[] = [
    {
      title: intl.formatMessage({ id: 'data.s/N' }), // 使用 intl 替换
      key: 'index',
      valueType: 'index',
      width: 60,
      dataIndex: 'pageIndex',
    },
    {
      title: intl.formatMessage({ id: 'data.acquisitionTime' }), // 采集时间
      dataIndex: 'collectTime',
      key: 'collectTime',
      valueType: 'dateTimeRange',
      width: 200,
      initialValue: [dayjs().startOf('day'), dayjs()],
      render: (_, record) => {
        return <span>{record.collectTime}</span>;
      },
      search: {
        transform: (value) => {
          return {
            startDate: value ? dayjs(value[0]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
            endDate: value ? dayjs(value[1]).format('YYYY-MM-DDTHH:mm:ss') : undefined,
          };
        },
      },
      fieldProps: {
        onCalendarChange: (dates: [Dayjs, Dayjs]) => {
          if (dates && dates.length === 2) {
            const [start, end] = dates;
            if (dayjs(end).diff(start, 'day') > 31) {
              message.warning(intl.formatMessage({ id: 'data.sDays' }));
            }
          }
        },
        disabledDate: (current: Dayjs | null) => {
          return current && current > dayjs().endOf('day');
        },
      },
    },
    {
      title: intl.formatMessage({ id: 'data.reportingTime' }), // 上报时间
      dataIndex: 'reportTime',
      key: 'reportTime',
      hideInSearch: true,
      width: 200,
      render: (_, record) => {
        return <span>{record.reportTime}</span>;
      },
    },
    {
      title: intl.formatMessage({ id: 'data.deviceModel' }), // 设备型号
      dataIndex: 'deviceModel',
      key: 'deviceModel',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.deviceFactory' }), // 设备厂家
      dataIndex: 'deviceManufacturer',
      key: 'deviceManufacturer',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.deviceID' }), // 设备ID
      dataIndex: 'deviceId',
      key: 'deviceId',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.workStatus' }), // 工作状态
      dataIndex: 'runningStatus',
      key: 'runningStatus',
      hideInSearch: true,
      width: 150,
      render: (_, record) => {
        return <span>{deviceWorkStatus[record.runningStatus] || record.runningStatus}</span>;
      },
    },
    // {
    //   title: intl.formatMessage({ id: 'data.gcbStatus' }), // 总断路器状态
    //   dataIndex: 'totalBreakerStatus',
    //   key: 'totalBreakerStatus',
    //   hideInSearch: true,
    //   width: 150,
    //   render: (_, record) => {
    //     return <span>{pcsStatus[record.totalBreakerStatus] || record.totalBreakerStatus}</span>;
    //   },
    // },
    // {
    //   title: intl.formatMessage({ id: 'data.gcbFault' }), // 总断路器故障
    //   dataIndex: 'totalBreakerFault',
    //   key: 'totalBreakerFault',
    //   hideInSearch: true,
    //   width: 150,
    //   render: (_, record) => {
    //     return <span>{pcsFault[record.totalBreakerFault] || pcsFault.totalBreakerFault}</span>;
    //   },
    // },
    {
      title: intl.formatMessage({ id: 'data.onlineStatus' }), // 在线状态
      dataIndex: 'onlineStatus',
      key: 'onlineStatus',
      hideInSearch: true,
      width: 150,
      render: (_, record) => {
        return <span>{deviceOnlineStatus[record.onlineStatus] || record.onlineStatus}</span>;
      },
    },
    {
      title: intl.formatMessage({ id: 'data.igbtTempa' }), // IGBT-A相温度
      dataIndex: 'igbtATemperature',
      key: 'igbtATemperature',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.igbtTempb' }), // IGBT-B相温度
      dataIndex: 'igbtBTemperature',
      key: 'igbtBTemperature',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.igbtTempc' }), // IGBT-C相温度
      dataIndex: 'igbtCTemperature',
      key: 'igbtCTemperature',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.ua' }), // A相电压（V）
      dataIndex: 'voltageA',
      key: 'voltageA',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.ub' }), // B相电压（V）
      dataIndex: 'voltageB',
      key: 'voltageB',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.uc' }), // C相电压（V）
      dataIndex: 'voltageC',
      key: 'voltageC',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.ia' }), // A相电流
      dataIndex: 'currentA',
      key: 'currentA',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.ib' }), // B相电流
      dataIndex: 'currentB',
      key: 'currentB',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.ic' }), // C相电流
      dataIndex: 'currentC',
      key: 'currentC',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.activePowerKw' }), // 有功功率（kW）
      dataIndex: 'activePower',
      key: 'activePower',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.reactivePowerKvar' }), // 无功功率（kvar）
      dataIndex: 'reactivePower',
      key: 'reactivePower',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.apparentPowerKva' }), // 视在功率（kVA）
      dataIndex: 'apparentPower',
      key: 'apparentPower',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.powerFactor' }), // 功率因数
      dataIndex: 'powerFactor',
      key: 'powerFactor',
      hideInSearch: true,
      width: 150,
    },
    {
      title: intl.formatMessage({ id: 'data.gridFrequency' }), // 电网频率
      dataIndex: 'gridFrequency',
      key: 'gridFrequency',
      hideInSearch: true,
      width: 150,
    },
  ];

  const filteredColumns = useMemo(() => {
    if (data.length === 0) return initialColumns;
    return initialColumns.filter(
      (column) =>
        column.dataIndex &&
        data.some((record) => record[column.dataIndex as keyof API.PcsPageData] !== null),
    );
  }, [data, initialColumns]);

  const fetchData = async (params: {
    current: number;
    pageSize: number;
    startDate: string;
    endDate: string;
  }) => {
    setLoading(true);
    const response = await historyDataControllerPcsDataPage({
      current: params.current,
      pageSize: params.pageSize,
      startDate: params.startDate,
      endDate: params.endDate,
      deviceCode,
      deviceType,
      areaId,
    });

    if (response.success && response.data && response.data?.records) {
      setData(
        response.data.records.map((record, index) => ({
          pageIndex: (params.current - 1) * params.pageSize + index + 1,
          collectTime: record.ts,
          reportTime: record.reportTime,
          deviceModel: record.product || null,
          deviceManufacturer: record.producer || null,
          deviceId: record.pcsCode,
          // @ts-ignore
          runningStatus:
            record.workState !== null
              ? // @ts-ignore
                deviceWorkStatus[record.workState] || record.workState
              : null,
          // totalBreakerStatus: record.stateInfo,
          // totalBreakerFault: record.faultInfo,
          // @ts-ignore
          onlineStatus:
            record.onlineState !== null
              ? // @ts-ignore
                deviceOnlineStatus[record.onlineState] || record.onlineState
              : null,
          igbtATemperature: record.igbta,
          igbtBTemperature: record.igbtb,
          igbtCTemperature: record.igbtc,
          voltageA: record.ua,
          voltageB: record.ub,
          voltageC: record.uc,
          currentA: record.ia,
          currentB: record.ib,
          currentC: record.ic,
          activePower: record.activePower,
          reactivePower: record.reactivePower,
          apparentPower: record.apparentPower,
          powerFactor: record.powerFactor,
          gridFrequency: record.gridFreq,
        })),
      );
      // @ts-ignore
      setTotal(response.data.total);
    } else {
      setData([]);
      setTotal(0);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData(params);
  }, [deviceCode, deviceType, areaId, params]);

  const handleTableChange = (pagination: { current: number; pageSize: number }) => {
    setParams((prevParams) => ({
      ...prevParams,
      current: pagination.current,
      pageSize: pagination.pageSize,
    }));
  };

  const handleSearch = (values: any) => {
    const startDate = dayjs(values.startDate);
    const endDate = dayjs(values.endDate);
    if (endDate.diff(startDate, 'day') > 31) {
      message.warning(intl.formatMessage({ id: 'data.sDays' }));
      return;
    }
    setParams((prevParams) => ({
      ...prevParams,
      startDate: values.startDate,
      endDate: values.endDate,
    }));
  };

  const handleReset = () => {
    setParams({
      current: 1,
      pageSize: 20,
      startDate: dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss'),
      endDate: dayjs().format('YYYY-MM-DDTHH:mm:ss'),
    });
    fetchData(params);
  };

  const scroll = {
    x: 'max-content',
    y: 'calc(100vh - 300px)',
  };

  const columnToAttrMap: Record<string, string> = {
    collectTime: 'ts', // 采集时间
    reportTime: 'reportTime', // 上报时间
    deviceModel: 'product', // 设备型号
    deviceManufacturer: 'producer', // 设备厂家
    deviceId: 'pcsCode', // 设备ID
    runningStatus: 'workState', // 工作状态
    // totalBreakerStatus: 'stateInfo', // 总断路器状态
    // totalBreakerFault: 'faultInfo', // 总断路器故障
    onlineStatus: 'onlineState', // 在线状态

    // IGBT温度
    igbtATemperature: 'igbta', // IGBT-A相温度
    igbtBTemperature: 'igbtb', // IGBT-B相温度
    igbtCTemperature: 'igbtc', // IGBT-C相温度

    // 电压相关
    voltageA: 'ua', // A相电压
    voltageB: 'ub', // B相电压
    voltageC: 'uc', // C相电压

    // 电流相关
    currentA: 'ia', // A相电流
    currentB: 'ib', // B相电流
    currentC: 'ic', // C相电流

    // 功率相关
    activePower: 'activePower', // 有功功率
    reactivePower: 'reactivePower', // 无功功率
    apparentPower: 'apparentPower', // 视在功率
    powerFactor: 'powerFactor', // 功率因数
    gridFrequency: 'gridFreq', // 电网频率
  };

  const exportDataReportFun = async (params: any) => {
    const startDate = dayjs(params.startDate);
    const endDate = dayjs(params.endDate);
    if (endDate.diff(startDate, 'day') > 3) {
      message.warning(intl.formatMessage({ id: 'data.selectTimeRange' }));
      return;
    }

    const attrNames =
      selectedColumns.length > 0
        ? selectedColumns
            .filter((col) => col !== 'index' && col !== 'pageIndex')
            .map((col) => columnToAttrMap[col] || col)
        : Object.values(columnToAttrMap);

    const exportParams: API.HistoryDataQuery = {
      areaId: Number(areaId),
      deviceType,
      deviceCode,
      startDate: dayjs(params.startDate).format('YYYY-MM-DD HH:mm:ss'),
      endDate: dayjs(params.endDate).format('YYYY-MM-DD HH:mm:ss'),
      attrNames,
    };

    await downloadFetch(exportDataReport, exportParams);
  };

  return (
    <div>
      <ProTable
        headerTitle={intl.formatMessage({ id: 'data.pcsDetails' })}
        search={{
          labelWidth: 80,
        }}
        columns={filteredColumns}
        scroll={scroll}
        columnsState={{
          value: Object.fromEntries(
            filteredColumns
              .filter((col) => col.dataIndex)
              .map((col) => [
                col.dataIndex,
                {
                  show:
                    selectedColumns.length === 0
                      ? true
                      : selectedColumns.includes(col.dataIndex as string),
                },
              ]),
          ),
          onChange: (stateMap) => {
            const newSelectedColumns = Object.entries(stateMap)
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
              .filter(([_, value]) => value.show)
              .map(([key]) => key);
            setSelectedColumns(newSelectedColumns);
          },
          persistenceKey: 'pcs-details-columns',
          persistenceType: 'localStorage',
        }}
        pagination={{
          current: params.current,
          pageSize: params.pageSize,
          total,
          onChange: (page, pageSize) => handleTableChange({ current: page, pageSize }),
        }}
        dataSource={data}
        loading={loading}
        onSubmit={handleSearch}
        onReset={handleReset}
        toolbar={{
          className: 'historyToobalr',
          actions: [
            <>
              <HandleBtn
                key="export"
                handleType="export"
                onClick={() => exportDataReportFun(params)}
              >
                {intl.formatMessage({ id: 'statistics.common.export' })}
              </HandleBtn>
              <Link key="monitor" to={`/stationmonitor/realtime?key=${selectedKeys}`}>
                {intl.formatMessage({ id: 'data.realtimeMonitor' })}
              </Link>
            </>,
          ],
        }}
      />
    </div>
  );
};

export default PCSDetails;
